package org.myh.excel.concurrent;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * ClassName: SimpleExcelBuffer
 * Description:
 * date: 2024/3/25 21:18
 *
 * @author Yu Han
 * @since JDK 1.8
 */
public class SimpleExcelBuffer extends AbstractDivisibleExcelBuffer<String[]> {


    public SimpleExcelBuffer(InputStream inputStream, int bufferSize, int rowCacheSize, int sheetIndex) {
        super(inputStream, bufferSize, rowCacheSize, sheetIndex,null);
    }


    @Override
    public void readExcel() throws Exception {
        // 1. 标记开始读取
        this.readState.set(READING);

        System.out.println("读取共有：" + rowNum + "行");

        int rowIndex = 1;
        int cellIndex = 0;

        //3 声明存储rowCacheSize行的数据 map存储区间数据 rows存储行数据
        HashMap<Integer, List<String[]>> map = new HashMap<>(2);
        List<String[]> rows = new ArrayList<>(this.rowCacheSize);
        //4 循环遍历表格
        for (Row row : this.sheet) {
            // 4.1默认第一行不读取
            if (rowIndex++ == 1) {
                map.put(rowIndex, rows);
                continue;
            }


            if (row != null) {
                String[] newArr = new String[row.getLastCellNum()];
                int fieldIndex = 0;
                // 4.4 获取第(i+1)行
                for (Cell cell : row) {
                    //获取单元格的内容，转成字符串
                    String stringCellValue = cell == null ? "" : cell.getStringCellValue();
                    //动态赋值
                    newArr[fieldIndex++] = stringCellValue;
                }
                // 4.5 存入List
                rows.add(newArr);

                // 4.6 数据量达到，存入Deque
                if ((rowIndex - 1) % rowCacheSize == 0) {
                    deque.addFirst(map);
                    // 5 重新初始化集合
                    map = new HashMap<>(2);
                    rows = new ArrayList<>(this.rowCacheSize);
                    map.put(rowIndex, rows);
                    readState.set(BE_DOING);
                }

                // 4.7 计算出最后一次数据的差值，存储最后一次数据
                if ((rowIndex - 1) == this.rowNum) {
                    System.out.println("最后一次插入:" + rowIndex);
                    deque.addFirst(map);
                    // 6.读取完成
                    readState.set(FINISHED);
                }
            }
        }
        closeResource();
    }
}
